package com.btpj.shop.controller;

import com.btpj.shop.dto.CommonResult;
import com.btpj.shop.dto.GoodsDto;
import com.btpj.shop.dto.param.GoodsParam;
import com.btpj.shop.entity.Goods;
import com.btpj.shop.service.GoodsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.BeanUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@Api(tags = "商品相关接口")
@RestController
@RequestMapping("/goods")
public class GoodsController {

    @Resource
    private GoodsService goodsService;

    @ApiOperation(value = "添加商品（必须拥有管理员权限）", notes = "商品价格单位为分(防止double计算的误差)")
    @PostMapping("/admin/add")
    public CommonResult<Void> addGoods(@RequestBody @Validated GoodsParam goodsParam) {
        if (goodsService.addGoods(goodsParam)) {
            return CommonResult.success("添加商品成功");
        }
        return CommonResult.error("服务器出错，添加商品失败");
    }

    @ApiOperation(value = "根据ID查询商品", notes = "商品价格单位为分(防止double计算的误差)")
    @ApiImplicitParam(name = "id", value = "商品Id", required = true, paramType = "path", dataType = "Long")
    @GetMapping("/details/{id}")
    public CommonResult<GoodsDto> getGoods(@PathVariable Long id) {
        if (!goodsService.exists(id)) {
            return CommonResult.error("不存在指定编号的商品");
        }
        Goods goods = goodsService.getGoods(id);
        GoodsDto goodsDto = new GoodsDto();
        BeanUtils.copyProperties(goods, goodsDto);
        return CommonResult.success(goodsDto);
    }

    @ApiOperation(value = "更新商品信息（必须拥有管理员权限）", notes = "商品价格单位为分(防止double计算的误差)")
    @ApiImplicitParam(name = "id", value = "商品Id", required = true, paramType = "path", dataType = "Long")
    @PutMapping("/admin/update/{id}")
    public CommonResult<Void> updateGoods(@PathVariable Long id, @RequestBody GoodsParam goodsParam) {
        if (!goodsService.exists(id)) {
            return CommonResult.error("不存在指定编号的商品");
        }

        String name = goodsParam.getName();
        if (name != null && !(name.length() > 0 && name.length() < 50)) {
            return CommonResult.error("name:商品名称必须在1～50个字符之间");
        }

        String description = goodsParam.getDescription();
        if (description != null && !(description.trim().length() > 0 && description.length() < 100)) {
            return CommonResult.error("description:商品简介必须在1～100个字符之间");
        }

        String imageUrl = goodsParam.getImageUrl();
        if (imageUrl != null && imageUrl.trim().length() > 0) {
            return CommonResult.error("imageUrl:商品图片URL不可为空");
        }

        String detailContent = goodsParam.getDetailContent();
        if (detailContent != null && detailContent.trim().length() > 0) {
            return CommonResult.error("detailContent:商品描述详情不可为空");
        }

        String keywords = goodsParam.getKeywords();
        if (keywords != null && !(keywords.length() > 0 && keywords.length() < 50)) {
            return CommonResult.error("keywords:商品简介必须在1～20个字符之间");
        }

        Byte sellStatus = goodsParam.getSellStatus();
        if (sellStatus != null && !(sellStatus == 0 || sellStatus == 1)) {
            return CommonResult.error("sellStatus:商品上架状态必须取值0:上架 1:下架");
        }

        if (goodsService.updateGoods(id, goodsParam)) {
            return CommonResult.success("商品修改成功");
        }
        return CommonResult.error("服务器出错，商品修改失败");
    }

    @ApiOperation(value = "批量修改商品上架信息（必须拥有管理员权限）")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "商品Id集合", required = true, paramType = "query", allowMultiple = true, dataType = "Long"),
            @ApiImplicitParam(name = "sellStatus", value = "商品上架状态（0:上架 1:下架）", required = true, paramType = "query", dataType = "Byte")
    })
    @PutMapping("/admin/updateSellStatus")
    public CommonResult<Void> updateGoods(Long[] ids,
                                          @Validated @Range(min = 0, max = 1, message = "商品上架状态必须取值0:上架 1:下架") Byte sellStatus) {
        for (Long id : ids) {
            if (!goodsService.exists(id)) {
                return CommonResult.error("不存在指定编号：" + id + "的商品");
            }
        }

        if (goodsService.updateGoodsSellStatus(ids, sellStatus)) {
            return CommonResult.success("商品修改成功");
        }
        return CommonResult.error("服务器出错，商品修改失败");
    }

    @ApiOperation(value = "删除商品（必须拥有管理员权限）")
    @ApiImplicitParam(name = "id", value = "商品Id", required = true, paramType = "path", dataType = "Long")
    @DeleteMapping("/admin/delete/{id}")
    public CommonResult<Void> updateGoods(@PathVariable Long id) {
        if (!goodsService.exists(id)) {
            return CommonResult.error("不存在指定编号的商品");
        }
        if (goodsService.deleteGoods(id)) {
            return CommonResult.success("商品删除成功");
        }
        return CommonResult.error("服务器出错，商品删除失败");
    }
}
